package com.changfen.service.impl;

import com.changfen.domain.Account;
import com.changfen.dto.OrderDto;
import com.changfen.feign.OrderClient;
import com.changfen.service.AccountService;
import com.changfen.service.TccAccountService;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author changfeng.chen@things-matrix.com
 * @date 2022/9/27 21:58
 **/
@Slf4j
@Service
public class TccAccountServiceImpl implements TccAccountService {
    @Resource
    private AccountService accountService;

    @Resource
    private OrderClient orderClient;


    @Override
    @Transactional
    public boolean tryCreate(BusinessActionContext businessActionContext, Long userId) {
        Account account = accountService.getOne(userId);
        if (BigDecimal.TEN.compareTo(account.getMoney()) > 0) {
            throw new RuntimeException("总额度少了");
        }

        orderClient.addTccOrder(
                OrderDto.builder()
                        .userId(String.valueOf(userId))
                        .commodityCode("c000001")
                        .count(10L)
                        .money(100L)
                        .build()
        ).okOrThrow();

        account.setMoney(account.getMoney().add(new BigDecimal(10000)));
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext businessActionContext) {
        log.info("TccAccountServiceImpl commit userId = {}", businessActionContext.getActionContext("userId"));
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {
        Account account = accountService.getOne(Long.parseLong(businessActionContext.getActionContext("userId").toString()));
        log.info("TccAccountServiceImpl rollback userId = {}", businessActionContext.getActionContext("userId"));
        return true;
    }
}
